package com.kyxx.topics.adapter;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.GradientDrawable;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.kyxx.topics.R;
import com.kyxx.topics.activity.JoinMemberActivity;
import com.kyxx.topics.activity.MemberDeatailActivity;
import com.kyxx.topics.activity.MemberPointActivity;
import com.kyxx.topics.activity.ShopQuanActivity;
import com.kyxx.topics.activity.ViewPagerActivity;
import com.kyxx.topics.activity.XiaoFeiJiLuActivity;
import com.kyxx.topics.bean.MemberDetailBean;
import com.kyxx.topics.bean.MemberPromotion;
import com.kyxx.topics.bean.MembershipCardBean;
import com.kyxx.topics.net.UrlUtils;
import com.kyxx.topics.utils.ScreenSizeUtils;
import com.kyxx.topics.utils.StringUtil;
import com.kyxx.topics.utils.ToastUtils;
import com.kyxx.topics.view.CircleImageView;
import com.kyxx.topics.zxing.encode.EncodingHandler;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import java.util.List;

public class MemberDetailAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private List<MemberDetailBean.Shop> shopList;
    private MemberDetailBean.Info infoBean;
    private List<MemberPromotion> promotions;
    private Context ctx;
    private ImageLoader imageLoader = ImageLoader.getInstance();
    private DisplayImageOptions options;
    private int mHeaderCount = 1;//头部View个数
    private MembershipCardBean bean;
    //item类型
    public static final int ITEM_TYPE_HEADER = 0;
    public static final int ITEM_TYPE_CONTENT = 1;
    private String[] bitmaps;
    private int shopPosition;

    public MemberDetailAdapter(Context paramContext, MemberDetailBean detailBean, List<MemberPromotion> promotion, MembershipCardBean bean,int shopPosition) {
        this.ctx = paramContext;
        this.shopList = detailBean.getList();
        this.shopPosition=shopPosition;
        this.infoBean = detailBean.getInfo();
        this.bean = bean;
        this.promotions = promotion;
        this.bitmaps = new String[promotions.size()];
        options = new DisplayImageOptions.Builder()
                // 设置图片在下载期间显示的图片
                .showImageOnLoading(R.mipmap.image_default)
                // 设置图片Uri为空或是错误的时候显示的图片
                .showImageForEmptyUri(R.mipmap.image_default)
                // 设置图片加载/解码过程中错误时候显示的图片
                .showImageOnFail(R.mipmap.image_default)
                .cacheInMemory(true)
                // 设置下载的图片是否缓存在内存中
                .cacheOnDisk(true)
                // 设置下载的图片是否缓存在SD卡中
                .bitmapConfig(Bitmap.Config.RGB_565)// 设置图片的解码类型
                // .displayer(new RoundedBitmapDisplayer(9999))
//                .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
                .resetViewBeforeLoading(false)
                .build();
    }

    //判断当前item是否是HeadView
    public boolean isHeaderView(int position) {
        return mHeaderCount != 0 && position < mHeaderCount;
    }

    @Override
    public int getItemCount() {
        return getContentItemCount() + mHeaderCount;
    }

    @Override
    public int getItemViewType(int position) {
        if (mHeaderCount != 0 && position < mHeaderCount) {
            //头部View
            return ITEM_TYPE_HEADER;
        } else {
            //内容View
            return ITEM_TYPE_CONTENT;
        }
    }

    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup paramViewGroup, int paramInt) {
        if (paramInt == ITEM_TYPE_HEADER) {
            return new HeaderViewHolder(LayoutInflater.from(this.ctx).inflate(R.layout.item_member_detail_header, paramViewGroup, false));
        } else if (paramInt == mHeaderCount) {
            return new ContentViewHolder(LayoutInflater.from(this.ctx).inflate(R.layout.item_member_detail, paramViewGroup, false));
        }
        return null;
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
        if (holder instanceof HeaderViewHolder) {
            ((HeaderViewHolder) holder).rl_lingquan.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(ctx, ShopQuanActivity.class);
                    intent.putExtra("shop_id", shopList.get(shopPosition).getSid());
                    ctx.startActivity(intent);
//                    ToastUtils.show(ctx, "领取优惠券");
                }
            });
            ((HeaderViewHolder) holder).rl_bangding.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(ctx, XiaoFeiJiLuActivity.class);
                    intent.putExtra("shop_id", shopList.get(shopPosition).getSid());
                    intent.putExtra("card_id", infoBean.getCard_id());
                    ctx.startActivity(intent);
//                    ToastUtils.show(ctx, "消费记录");
                }
            });
            if (!StringUtil.isEmpty(infoBean.getType_card_image())) {
                imageLoader.displayImage(UrlUtils.BASEHTTP + infoBean.getType_card_image(), ((HeaderViewHolder) holder).cv_member_detail_header_icon, options);
                ((HeaderViewHolder) holder).cv_member_detail_header_icon.setVisibility(View.VISIBLE);
                ((HeaderViewHolder) holder).tv_member_icon.setVisibility(View.GONE);
            } else {
                ((HeaderViewHolder) holder).cv_member_detail_header_icon.setVisibility(View.GONE);
                ((HeaderViewHolder) holder).tv_member_icon.setVisibility(View.VISIBLE);
                ((HeaderViewHolder) holder).tv_member_icon.setText(bean.getType_name().substring(0, 1));
                GradientDrawable drawable1 = (GradientDrawable) ((HeaderViewHolder) holder).tv_member_icon.getBackground();
                if (bean.getShop_color() == null || bean.getShop_color().contains(",")) {
                    bean.setShop_color("FFFDBB2B");
                } else {
                    bean.setShop_color("FF" + bean.getShop_color());
                }
                int a = new java.math.BigInteger("ffffff", 16).intValue();
                int b = new java.math.BigInteger(bean.getShop_color(), 16).intValue();
                drawable1.setColor(b);
                if (a == b) {
                    ((HeaderViewHolder) holder).tv_member_icon.setTextColor(ctx.getResources().getColor(R.color.black));
                } else {
                    ((HeaderViewHolder) holder).tv_member_icon.setTextColor(ctx.getResources().getColor(R.color.white));
                }
            }
            ((HeaderViewHolder) holder).tv_member_detail_header_name.setText(bean.getType_name());
            GradientDrawable drawable = (GradientDrawable) ((HeaderViewHolder) holder).rl_member_detail_header.getBackground();
            if (bean.getShop_color() == null || bean.getShop_color().contains(",")) {
                bean.setShop_color("FFFDBB2B");
            } else {
                bean.setShop_color("FF" + bean.getShop_color());
            }
            int b = new java.math.BigInteger(bean.getShop_color(), 16).intValue();
            drawable.setColor(b);
            if (!"".equals(infoBean.getCardnum()) || !"".equals(infoBean.getMobile())) {
                ((HeaderViewHolder) holder).ll.setVisibility(View.VISIBLE);
                ((HeaderViewHolder) holder).fl_member_to_join.setVisibility(View.GONE);

                ((HeaderViewHolder) holder).tv_member_detail_header_card_num.setText(
                        infoBean == null ?
                                "" : "".equals(infoBean.getCardnum()) ? ("".equals(infoBean.getMobile()) ? "" : "TEL." + infoBean.getMobile()) : "NO." + infoBean.getCardnum());
                if (infoBean.getIs_private() == 0) {
                    ((HeaderViewHolder) holder).tv_member_detail_header_jifen.setVisibility(View.VISIBLE);
                    ((HeaderViewHolder) holder).tv_member_detail_header_jifen.setText(infoBean == null ? "会员积分:0" : "会员积分:" + infoBean.getPoint());
                } else {
                    ((HeaderViewHolder) holder).tv_member_detail_header_jifen.setVisibility(View.GONE);
                }
                ((HeaderViewHolder) holder).iv_member_detail_header_num.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (StringUtil.isChineseChar(infoBean.getCardnum()) || "".equals(infoBean.getCardnum())) {
                            if (StringUtil.isChineseChar(infoBean.getMobile()) || "".equals(infoBean.getMobile())) {
                                ToastUtils.show(ctx, "请输入正确的会员卡号");
                            } else {
                                dialog(infoBean.getMobile());
                            }
                        } else {
                            dialog(infoBean.getCardnum());
                        }
                    }
                });
            } else {
                ((HeaderViewHolder) holder).ll.setVisibility(View.GONE);
                ((HeaderViewHolder) holder).fl_member_to_join.setVisibility(View.VISIBLE);
                ((HeaderViewHolder) holder).iv_member_add.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        ctx.startActivity(new Intent(ctx, JoinMemberActivity.class).putExtra("shop_id", shopList.get(shopPosition).getSid()).putExtra("CardBean", bean).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                        ((MemberDeatailActivity) ctx).finish();
                    }
                });
            }
            ((HeaderViewHolder) holder).tv_member_detail_header_jifen.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    ctx.startActivity(new Intent(ctx, MemberPointActivity.class).putExtra("shop_id", shopList.get(shopPosition).getSid()).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                }
            });
        } else if (holder instanceof ContentViewHolder) {
            imageLoader.displayImage(UrlUtils.BASEHTTP + promotions.get(position - mHeaderCount).getImageurl(), ((ContentViewHolder) holder).iv_activity_icon, options);
            imageLoader.loadImage(UrlUtils.BASEHTTP + promotions.get(position - mHeaderCount).getImageurl(), options, new ImageLoadingListener() {
                @Override
                public void onLoadingStarted(String imageUri, View view) {

                }

                @Override
                public void onLoadingFailed(String imageUri, View view, FailReason failReason) {

                }

                @Override
                public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                    ((ContentViewHolder) holder).iv_activity_icon.setImageBitmap(loadedImage);
                }

                @Override
                public void onLoadingCancelled(String imageUri, View view) {

                }
            });
            bitmaps[position - mHeaderCount] = UrlUtils.BASEHTTP + promotions.get(position - mHeaderCount).getImageurl();
            ((ContentViewHolder) holder).iv_activity_icon.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    ctx.startActivity(new Intent(ctx, ViewPagerActivity.class).putExtra("bitmap", bitmaps).putExtra("index", (position - mHeaderCount)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                }
            });
        }
    }

    public int getContentItemCount() {
        return promotions == null ? 0 : this.promotions.size();
    }

    public class HeaderViewHolder extends RecyclerView.ViewHolder {
        TextView tv_member_detail_header_name, tv_member_icon;
        CircleImageView cv_member_detail_header_icon;
        ImageView iv_member_detail_header_num;
        FrameLayout fl_member_to_join;
        TextView tv_member_detail_header_card_num;
        TextView tv_member_detail_header_jifen;
        ImageView iv_member_add;
        RelativeLayout rl_member_detail_header;
        RelativeLayout rl_lingquan;
        RelativeLayout rl_bangding;
        LinearLayout ll;

        public HeaderViewHolder(View itemView) {
            super(itemView);
            tv_member_icon = (TextView) itemView.findViewById(R.id.tv_member_icon);
            tv_member_detail_header_name = (TextView) itemView.findViewById(R.id.tv_member_detail_header_name);
            tv_member_detail_header_jifen = (TextView) itemView.findViewById(R.id.tv_member_detail_header_jifen);
            tv_member_detail_header_card_num = (TextView) itemView.findViewById(R.id.tv_member_detail_header_card_num);
            fl_member_to_join = (FrameLayout) itemView.findViewById(R.id.fl_member_to_join);
            cv_member_detail_header_icon = (CircleImageView) itemView.findViewById(R.id.cv_member_detail_header_icon);
            iv_member_detail_header_num = (ImageView) itemView.findViewById(R.id.iv_member_detail_header_num);
            iv_member_add = (ImageView) itemView.findViewById(R.id.iv_member_add);
            rl_member_detail_header = (RelativeLayout) itemView.findViewById(R.id.rl_member_detail_header);
            rl_lingquan = (RelativeLayout) itemView.findViewById(R.id.rl_lingquan);
            rl_bangding = (RelativeLayout) itemView.findViewById(R.id.rl_bangding);
            ll = (LinearLayout) itemView.findViewById(R.id.ll);
        }
    }

    public class ContentViewHolder extends RecyclerView.ViewHolder {
        ImageView iv_activity_icon;

        public ContentViewHolder(View itemView) {
            super(itemView);
            iv_activity_icon = (ImageView) itemView.findViewById(R.id.iv_activity_icon);
            iv_activity_icon.setScaleType(ImageView.ScaleType.FIT_CENTER);
            iv_activity_icon.setAdjustViewBounds(true);
        }
    }

    @Override
    public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) {
        super.onViewAttachedToWindow(holder);
        ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
        if (lp != null && lp instanceof StaggeredGridLayoutManager.LayoutParams) {
            StaggeredGridLayoutManager.LayoutParams p = (StaggeredGridLayoutManager.LayoutParams) lp;
            p.setFullSpan(holder.getLayoutPosition() == 0);
        }
    }

    private void dialog(String code) {
        Dialog dialog = new Dialog(ctx);
        View mDialogView = View.inflate(ctx, R.layout.dialog_scan_code, null);
        ImageView img = (ImageView) mDialogView.findViewById(R.id.iv_scan_code);
        TextView tv = (TextView) mDialogView.findViewById(R.id.tv_scan_code_num);
        mDialogView.setMinimumHeight((int) (ScreenSizeUtils.getInstance(ctx).getScreenHeight() * 0.2f));
        dialog.setContentView(mDialogView);
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (ScreenSizeUtils.getInstance(ctx).getScreenWidth() * 0.88f);
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.CENTER;
        dialogWindow.setAttributes(lp);
        img.setImageBitmap(createBarCode(code));
        tv.setText(code);
        dialog.show();
    }

    private Bitmap createBarCode(String key) {
        Bitmap qrCode = null;
        try {
            qrCode = EncodingHandler.createBarCode(key, (int) (ScreenSizeUtils.getInstance(ctx).getScreenWidth() * 0.7f), (int) (ScreenSizeUtils.getInstance(ctx).getScreenHeight() * 0.17f));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return qrCode;
    }
}